package com.relivethefuture.bidule.model
{
	import flash.filesystem.File;
	import flash.filesystem.FileStream;
	import flash.filesystem.FileMode;
	import flash.xml.XMLNode;
	
	public class Group
	{
		private var _author:String;
		private var _description:String;
		private var _email:String;
		
		[Bindable]
		public var name:String;
		
		public var displayName:String;
		
		[Bindable]
		public var type:String;
		
		/**
		 * Full path to file
		 **/
		public var file:String;
		
		public var displayPath:String;
		public var version:String;
		
		private var palettePath:Array;
		
		private var xml:XML;
		private var descriptionNode:XML;
		
		private var changed:Boolean;
		
		public function Group()
		{
			description = "";
			email = "";
			changed = false;
		}

		[Bindable]		
		public function set author(a:String):void
		{
			if(a != _author)
			{
				_author = a;
				changed = true;
			}
		}
		
		public function get author():String
		{
			return _author;
		}

		[Bindable]		
		public function set description(d:String):void
		{
			if(d != _description)
			{
				_description = d;
				changed = true;
			}
		}
		
		public function get description():String
		{
			return _description;
		}
		
		[Bindable]
		public function set email(e:String):void
		{
			if(e != _email)
			{
				_email = e;
				changed = true;
			}
		}
		
		public function get email():String
		{
			return _email;
		}
		
		public function parse():Boolean
		{
			if(file == null)
			{
				trace("Path isnt set");
				return false;
			}
			
			var f:File = new File(file);
			if(f.exists)
			{
				var stream:FileStream = new FileStream();
				stream.open(f, FileMode.READ);
				xml = new XML(stream.readUTFBytes(stream.bytesAvailable));
				var success:Boolean = parseXML();
		 		stream.close();
		 		return success;
		 	}
		 	else
		 	{
		 		trace("Group file doesnt exist : " + file);
		 	}
		 	return false;
		}
	
		private function parseXML():Boolean
		{
			if(xml.BiduleGroup == undefined)
			{
				trace("No group found for : " + file);
				return false;
			}
			
			displayName = xml.BiduleGroup.@displayName;
			displayPath = xml.BiduleGroup.@displayPath;
			if(displayPath != null && displayPath.length > 0)
			{
				palettePath = displayPath.split("\\t");
			}
			else
			{
				palettePath = [displayName];
			}
			
			_author = xml.BiduleGroup.@author;
			type = xml.BiduleGroup.@type;
			version = xml.BiduleGroup.@version;
			var readme:XMLList = xml.BiduleGroup.Bidule.(@displayName=="README").Parameter;

			if(readme.length() > 0)
			{
				parseReadme(readme[0]);
			}
			else
			{

				// create description node
				var commentNode:XML = <Bidule id="UID_2345678910" type="com.plogue.Comment" displayName="README" processingMode="process">
									<Geometry x="0" y="0" w="0" h="0"/>
									<ChannelConfig numSampleIn="0" numSampleOut="0" numMidiIn="0" numMidiOut="0" numFreqIn="0" numFreqOut="0" numMagIn="0" numMagOut="0"/>
									<Gui state="normal" hidden="true" generic="true">
										<Geometry x="0" y="0" w="411" h="298"/>
									</Gui>
									<Parameter id="0" userMin="0" userMax="0" lockedForRandom="true" mutationFactor="0"></Parameter>
								</Bidule>
				
				var params:XMLList = xml.BiduleGroup[0].Parameter;
				xml.BiduleGroup[0].insertChildAfter(params[params.length() - 1],commentNode);
				descriptionNode = commentNode.Parameter[0];
			}
			
			return true;
		}
		
		private function parseReadme(readme:XML)
		{
			var r:String = readme[0].toString();
			var contactIndex:Number = r.indexOf("CONTACT:");
			if(contactIndex != -1)
			{
				var eIndex:Number = contactIndex + 8;
				_email = r.substr(eIndex);
				_description = r.substr(0,contactIndex);
			}
			else
			{
				_email = "";
				_description = r;
			}
			
			descriptionNode = readme[0];
		}
		
		public function getPalettePath():Array
		{
			return palettePath;
		}
		
		public function setPalettePath(path:Array):void
		{
			trace("Set palette path : " + name + " : " + path);
			palettePath = path;
			displayPath = palettePath.join("\\t");
			changed = true;
		}
		
		public function save():void
		{
			if(!changed) return;
			
			trace("Saving group " + name + " : " + _author + " : " + _description);

			if(descriptionNode.children().length() == 0)
			{
				descriptionNode.appendChild(_description + "\n" + _email);
			}
			else
			{
				descriptionNode.children()[0] = _description + "\n" + _email;
			}
			
			xml.BiduleGroup.@author = _author;
			xml.BiduleGroup.@displayPath = displayPath;
			try
			{
				var stream:FileStream = new FileStream();
				var f:File = new File(file);
				stream.open(f, FileMode.WRITE);
				stream.writeUTFBytes('<?xml version="1.0" encoding="utf-8"?>\n' + xml.toXMLString());
				stream.close();
				changed = false;
			}
			catch (error:Error)
			{
				trace("Couldnt save group " + name);
			}
		}
	}
}